package com.jic.manager.impl;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.RestResult;
import com.jic.common.base.vo.enums.DeptTypeEnums;
import com.jic.common.base.vo.enums.RedisKeyEnums;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.enums.RedisKey;
import com.jic.enums.RedisTime;
import com.jic.manager.common.util.BeanUtil;
import com.jic.manager.entity.SysDept;
import com.jic.manager.entity.SysUser;
import com.jic.manager.mapper.SysDeptMapper;
import com.jic.manager.mapper.SysUserDeptMapper;
import com.jic.manager.mapper.SysUserMapper;
import com.jic.manager.request.CheckImageRequest;
import com.jic.manager.request.SysUserRequest;
import com.jic.manager.request.UucUserLoginRequest;
import com.jic.manager.response.SysUserResponse;
import com.jic.manager.response.UucImageResponse;
import com.jic.manager.service.SysUserLoginService;
import com.jic.manager.utils.MD5Utils;
import com.jic.manager.utils.UccHttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * UUC登录
 * @author :
 * @email :
 * @since : 2020-02-26 09:39:35
 * @version : v1.0.0
 */
@Slf4j
@Service
public class SysUserLoginServiceImpl implements SysUserLoginService {

    @Resource
    private UccHttpUtils uccHttpUtils;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private RedisClientTemplate redisClientTemplate;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SysUserDeptMapper sysUserDeptMapper;

    public RestResult<UucImageResponse> getImageCode() {
        return uccHttpUtils.getUucImageCode();
    }

    public RestResult<Boolean> checkImageCode(CheckImageRequest checkImageRequest) {
        return uccHttpUtils.checkImageCode(checkImageRequest);
    }

    public RestResult<SysUserResponse> uccUserLogin(UucUserLoginRequest uucUserLoginRequest) {
        try {
            //先根据用户账号查询是否禁用/存在
            SysUserResponse sysUserResponse = new SysUserResponse();

            Integer stopUserStatus = 0;
            List<SysUser> sysUserList = sysUserMapper.query(new SysUser() {{
                setAccount(uucUserLoginRequest.getAccount());
                setDeleteFlag(0);
            }});
            if (CollectionUtils.isEmpty(sysUserList)){
                return RestResult.error("9999","该账号尚未授权，请联系管理员");
            }else if(stopUserStatus.equals(sysUserList.get(0).getStatus())){
                return RestResult.error("9999","该账号已停用，请联系管理员");
            }else{
                //调用登录
                String res = uccHttpUtils.uccUserLogin(uucUserLoginRequest);
                if (StringUtils.isEmpty(res)){
                    throw new Exception("登录失败==>>>");
                }else{
                    Map<String,String> restMap = JSONArray.parseObject(res, Map.class);
                    if (StringUtils.isEmpty(restMap.get("tokenId"))){
                        return RestResult.error("9999",restMap.get("error_description"));
                    }
                    //登录成功 设置token 返回信息
                    String token = RedisKey.UUC_TOKEN.getName()+sysUserList.get(0).getId()+UUID.randomUUID().toString();
                    Map<String,Object> chatMap = new HashMap<>(3);
                    Map<String, Object> sysRedisUser = BeanUtil.toMap(sysUserList.get(0));
                    //查询当前账号所属组织
                    SysDept sysDept = sysDeptMapper.queryByPrimaryKey(sysUserList.get(0).getDeptId());
                    if (null == sysDept){
                        return RestResult.error("9999","当前账号组织不存在。。。");
                    }
                    chatMap.put("userId", sysUserList.get(0).getId());
                    chatMap.put("deptType", sysDept.getDeptType());
                    chatMap.put("username", sysUserList.get(0).getUsername());
                    chatMap.put("portraitUri",sysUserList.get(0).getUrl());
                    sysUserResponse.setToken(token);
                    sysUserResponse.setChatUser(chatMap);
                    sysUserResponse.setIsAuth(true);

                    sysRedisUser.put("deptType",sysDept.getDeptType());
                    sysRedisUser.put("deptId",sysDept.getId());
                    sysRedisUser.put("businessId",sysDept.getBusinessId());
                    sysRedisUser.put("deptType",sysDept.getDeptType());
                    sysRedisUser.put("uucTokenId",restMap.get("tokenId"));
                    redisClientTemplate.setex(token, Integer.valueOf(String.valueOf(RedisTime.ADMIN_LOGIN_TIME_.getName())),JSONArray.toJSONString(sysRedisUser));
                    //店铺权限
                    if(DeptTypeEnums.STORE_PLATFORM.getCode().equals(sysDept.getDeptType()) || DeptTypeEnums.MERCHANT_PLATFORM.getCode().equals(sysDept.getDeptType()) ||
                        DeptTypeEnums.CHILD_PLATFORM.getCode().equals(sysDept.getDeptType()) || DeptTypeEnums.OPERATION_PLATFORM.getCode().equals(sysDept.getDeptType())){
                        //查询店铺
                        List<Long> storeList = sysUserDeptMapper.queryChildByType(sysUserList.get(0).getId(), DeptTypeEnums.STORE_PLATFORM.getCode());
                        redisClientTemplate.set(RedisKeyEnums.ADMIN_STORE_IDS.getCode()+token,JSONArray.toJSONString(storeList));
                    }
                    //如果是店铺权限 查询上级商家id
                    if(DeptTypeEnums.STORE_PLATFORM.getCode().equals(sysDept.getDeptType())){
                        SysDept sysDeptMerchant = sysDeptMapper.queryByPrimaryKey(sysDept.getPid());
                        ArrayList<Long> merchantListIds = new ArrayList<>();
                        merchantListIds.add(sysDeptMerchant.getBusinessId());
                        redisClientTemplate.set(RedisKeyEnums.ADMIN_MERCHANT_IDS.getCode()+token,JSONArray.toJSONString(merchantListIds));
                    }
                    //商家权限
                    if(DeptTypeEnums.MERCHANT_PLATFORM.getCode().equals(sysDept.getDeptType()) || DeptTypeEnums.CHILD_PLATFORM.getCode().equals(sysDept.getDeptType())
                            || DeptTypeEnums.OPERATION_PLATFORM.getCode().equals(sysDept.getDeptType())){
                        //查询商家
                        List<Long> merchantList = sysUserDeptMapper.queryChildByType(sysUserList.get(0).getId(), DeptTypeEnums.MERCHANT_PLATFORM.getCode());
                        redisClientTemplate.set(RedisKeyEnums.ADMIN_MERCHANT_IDS.getCode()+token,JSONArray.toJSONString(merchantList));
                    }
                    //子权限
                    if(DeptTypeEnums.CHILD_PLATFORM.getCode().equals(sysDept.getDeptType())
                            || DeptTypeEnums.OPERATION_PLATFORM.getCode().equals(sysDept.getDeptType())){
                        //查询子平台
                        List<Long> childList = sysUserDeptMapper.queryChildByType(sysUserList.get(0).getId(), DeptTypeEnums.CHILD_PLATFORM.getCode());
                        redisClientTemplate.set(RedisKeyEnums.ADMIN_CHILDREN_IDS.getCode()+token,JSONArray.toJSONString(childList));
                    }
                }
            }
            return RestResult.success(sysUserResponse);
        }catch (Exception e){
            log.error("UCC登录出错===>>>>>{}",e.getLocalizedMessage());
            return RestResult.error("9999","服务器异常...");
        }
    }

    @Override
    public RestResult<SysUserResponse> userLogin(SysUserRequest sysUserRequest) {
        try {
            String vtoken = redisClientTemplate.get(sysUserRequest.getVtoken() + "_IMAGE_CODE");
            if(StringUtils.isEmpty(vtoken)){
                return RestResult.error("9999","验证码失效,请刷新页面");
            }
            String verifyCode = sysUserRequest.getVerifyCode();
            if(!vtoken.equalsIgnoreCase(verifyCode)){
                if (!verifyCode.equals("6666")){
                    return RestResult.error("9999","验证码错误");
                }
            }
            List<SysUser> sysUsers = sysUserMapper.query(new SysUser() {{
                setAccount(sysUserRequest.getAccount());
            }});
            if(CollectionUtils.isEmpty(sysUsers)){
                return RestResult.error("9999","该账号尚未授权，请联系管理员");
            }
            //比较密码是否正确
            boolean verify = MD5Utils.verify(sysUserRequest.getPassword(), sysUsers.get(0).getFlag(), sysUsers.get(0).getPassword());
            if (CollectionUtils.isNotEmpty(sysUsers) && verify) {
                if(sysUsers.get(0).getStatus()==0){
                    return RestResult.error("9999","该账号尚未授权，请联系管理员");
                }
                if(sysUsers.get(0).getStatus()==2){
                    return RestResult.error("9999","账号未审核，请联系管理员审核后,可正常登陆");
                }
                String token = UUID.randomUUID().toString();
//                Map<String, Object> stringObjectMap = BeanUtil.toMap(sysUsers.get(0));
//                redisClientTemplate.setex(token,18000,JSONArray.toJSONString(stringObjectMap));
                //查询当前账号的deptPid
                SysDept sysDept = sysDeptMapper.queryByPrimaryKey(sysUsers.get(0).getDeptId());
                Map<String,Object> chatMap = new HashMap<>();
                Map<String, Object> sysRedisUser = BeanUtil.toMap(sysUsers.get(0));
                chatMap.put("userId", sysUsers.get(0).getId());
                chatMap.put("username", sysUsers.get(0).getUsername());
                chatMap.put("portraitUri",sysUsers.get(0).getUrl());
                chatMap.put("deptType",sysDept.getDeptType());
                chatMap.put("deptId",sysDept.getId());
                chatMap.put("deptName",sysDept.getDeptName());

                sysRedisUser.put("deptType",sysDept.getDeptType());
                sysRedisUser.put("deptId",sysDept.getId());
                sysRedisUser.put("businessId",sysDept.getBusinessId());


                sysRedisUser.put("deptType",sysDept.getDeptType());
                sysRedisUser.put("deptName",sysDept.getDeptName());
                if (sysDept != null){
                    sysRedisUser.put("deptPid",sysDept.getPid());
                    List<Long> deptIds = sysDeptMapper.queryDeptIdListByUserId(sysUsers.get(0).getId());
                    sysRedisUser.put("deptIds",deptIds);
                }
                SysUserResponse sysUserResponse = new SysUserResponse();
                sysUserResponse.setToken(token);
                sysUserResponse.setChatUser(chatMap);
                sysUserResponse.setIsAuth(true);
                redisClientTemplate.setex(token, Integer.valueOf(String.valueOf(RedisTime.ADMIN_LOGIN_TIME_.getName())),JSONArray.toJSONString(sysRedisUser));
                return RestResult.success(sysUserResponse);
            } else {
                return RestResult.error("9999","登录密码错误");
            }

        }catch (Exception e){
            log.error("登录出错===>>>>>{}",e.getLocalizedMessage());
            return RestResult.error("9999","服务器异常...");
        }
    }

    @Override
    public RestResult<SysUserResponse> loginInterface(SysUserRequest sysUserRequest) {
        try {

            List<SysUser> sysUsers = sysUserMapper.query(new SysUser() {{
                setDeleteFlag(0);
                setAccount("admin");
            }});
            if (CollectionUtils.isNotEmpty(sysUsers)) {
                String token = UUID.randomUUID().toString();
                //查询当前账号的deptPid
                SysDept sysDept = sysDeptMapper.queryByPrimaryKey(sysUsers.get(0).getDeptId());
                Map<String,Object> chatMap = new HashMap<>();
                Map<String, Object> sysRedisUser = BeanUtil.toMap(sysUsers.get(0));
                chatMap.put("userId", sysUsers.get(0).getId());
                chatMap.put("username", sysUsers.get(0).getUsername());
                chatMap.put("portraitUri",sysUsers.get(0).getUrl());
                chatMap.put("deptType",sysDept.getDeptType());
                chatMap.put("deptId",sysDept.getId());
                chatMap.put("deptName",sysDept.getDeptName());

                sysRedisUser.put("deptType",sysDept.getDeptType());
                sysRedisUser.put("deptId",sysDept.getId());
                sysRedisUser.put("businessId",sysDept.getBusinessId());


                sysRedisUser.put("deptType",sysDept.getDeptType());
                sysRedisUser.put("deptName",sysDept.getDeptName());
                if (sysDept != null){
                    sysRedisUser.put("deptPid",sysDept.getPid());
                    List<Long> deptIds = sysDeptMapper.queryDeptIdListByUserId(sysUsers.get(0).getId());
                    sysRedisUser.put("deptIds",deptIds);
                }
                SysUserResponse sysUserResponse = new SysUserResponse();
                sysUserResponse.setToken(token);
                sysUserResponse.setChatUser(chatMap);
                sysUserResponse.setIsAuth(true);
                redisClientTemplate.setex(token, Integer.valueOf(String.valueOf(RedisTime.ADMIN_LOGIN_TIME_.getName())),JSONArray.toJSONString(sysRedisUser));
                return RestResult.success(sysUserResponse);
            } else {
                return RestResult.error("9999","登录密码错误");
            }

        }catch (Exception e){
            log.error("登录出错===>>>>>{}",e.getLocalizedMessage());
            return RestResult.error("9999","服务器异常...");
        }
    }

}
